package com.soul.dj.util.http.json;

import android.util.Log;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonProcessUtil
{
	private static final String TAG = "JsonProcessUtil";
	private static ObjectMapper	mapper;

	static
	{
		mapper = new ObjectMapper();
		mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	}
	
	
	public static <T> Json<T> jsonToBean(String jsonString,Class<T> objClass) throws JsonParseErrorException
	{
		JavaType javaType = mapper.getTypeFactory().constructParametricType(Json.class, objClass);  
		Json<T> json = null;
		
		try
		{
			json = (Json<T>)mapper.readValue(jsonString , javaType);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			Log.e(TAG , "JSON解析失败",e);
			throw new JsonParseErrorException("JSON解析失败!");
		}
		
		return json;
	}
	
	public static <T> T jsonToBean2(String jsonString,Class<T> objClass) throws JsonParseErrorException
	{
		T t = null;
		
		try
		{
			t = (T)mapper.readValue(jsonString , objClass);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			Log.e(TAG , "JSON解析失败",e);
			throw new JsonParseErrorException("JSON解析失败!");
		}
		
		return t;
	}
	
	public static  Json jsonToBean(String jsonString) throws JsonParseErrorException
	{
		Json json = null;
		
		try
		{
			json = (Json)mapper.readValue(jsonString,Json.class);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			Log.e(TAG , "JSON解析失败",e);
			throw new JsonParseErrorException("JSON解析失败!");
		}
		
		return json;
	}
	
	public static String beanToJson(Object obj) throws JsonProcessingException 
	{
		return mapper.writeValueAsString(obj);
	}

	public static ObjectMapper getMapper()
	{
		return mapper;
	}
}
